import os
import shutil
import re
from pathlib import Path

def create_numbered_dirs():
    # Create directories from 1 to 100 in onepic
    onepic_dir = Path('onepic')
    for i in range(1, 501):
        dir_path = onepic_dir / str(i)
        dir_path.mkdir(exist_ok=True)

def extract_number(dirname):
    # 如果目录名是数字，则直接返回
    if dirname.isdigit():
        return int(dirname)
    """
    从任意前缀格式如"任意前缀X_日期"中提取数字X。
    
    参数:
    dirname (str): 文件或目录名。
    
    返回:
    int: 提取出的数字；如果未找到匹配，则返回0。
    """
    # 正则表达式匹配任何以非数字字符开头，紧接着是数字和下划线及日期的字符串
    match = re.search(r'^\D*(\d+)_\d{2}_\d{2}_\d{4}', dirname)
    if match:
        return int(match.group(1))  # 提取并返回数字部分
    return 0  # 如果没有找到匹配项，则返回0

def natural_sort_key(s):
    """用于实现提取文件夹的数字的自然排序"""
    # 如果目录名是数字，则直接返回
    # 如果目录名是数字，则直接返回
    return [int(text) if text.isdigit() else text.lower()
            for text in re.split('([0-9]+)', str(s))]

def process_panels():
    extracted_panels_dir = Path('extracted_panels')
    onepic_dir = Path('onepic')
    current_target_dir = 1
    
    # Get all panel directories sorted by the number in their names
    panel_dirs = sorted([d for d in extracted_panels_dir.iterdir() if d.is_dir()],
                       key=lambda x: extract_number(x.name))

    panel_dirs.sort(key=natural_sort_key)
    
    # Process each directory
    for panel_dir in panel_dirs:
        # Get all panel files in the current directory
        panel_files = sorted([f for f in panel_dir.glob('panel_*.jpg')])
        
        # Process each panel file
        for panel_file in panel_files:
            # If we've exceeded directory 100, break
            if current_target_dir > 500:
                print(f"Warning: More panels than available directories (200)")
                return
                
            # Copy the file to the target directory
            target_dir = onepic_dir / str(current_target_dir)
            target_file = target_dir / panel_file.name
            shutil.copy2(panel_file, target_file)
            print(f"Copied {panel_file} to {target_file}")
            current_target_dir += 1

def cleanup_empty_dirs():
    # Remove empty directories in onepic
    onepic_dir = Path('onepic')
    for i in range(1, 501):
        dir_path = onepic_dir / str(i)
        if dir_path.exists() and not any(dir_path.iterdir()):
            dir_path.rmdir()
            print(f"Removed empty directory: {dir_path}")

def main():
    print("Creating numbered directories...")
    create_numbered_dirs()
    
    print("\nProcessing and copying panel files...")
    process_panels()
    
    print("\nCleaning up empty directories...")
    cleanup_empty_dirs()
    
    print("\nProcess completed!")
    #复制onepic中的文件到bofan目录中
    onepic_dir = Path('onepic')
    bofan_dir = Path('bofan')
    for i in range(1, 501):
        dir_path = onepic_dir / str(i)
        if dir_path.exists():
            shutil.copytree(dir_path, bofan_dir / str(i))

if __name__ == "__main__":
    main() 